package com.tjvib.view.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.jjoe64.graphview.DefaultLabelFormatter;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.LegendRenderer;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
import com.jjoe64.graphview.series.PointsGraphSeries;
import com.tjvib.Constants;
import com.tjvib.R;
import com.tjvib.base.BaseActivity;
import com.tjvib.util.LogUtil;
import com.tjvib.util.Manager.DataSetManager;
import com.tjvib.presenter.BasePresenter;
import com.tjvib.util.Manager.AppManager;
import com.tjvib.util.Manager.UserManager;
import com.tjvib.util.PoiUtil;
import com.tjvib.util.PressUtil;
import com.tjvib.util.ToastUtil;
import com.tjvib.view.dialog.LoadingDialog;
import com.tjvib.widget.TitleLayout;

import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class HumanActivity extends BaseActivity {

    private TextView human_tv_real, human_tv_choose;
    private GraphView human_gv_data;
    private Button human_btn_export;
    private TitleLayout human_tit;

    private LineGraphSeries<DataPoint> responseSeries = new LineGraphSeries<>(),
            simuSeries = new LineGraphSeries<>();
    private PointsGraphSeries<DataPoint> oPoint = new PointsGraphSeries<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_human;
    }

    @Override
    protected boolean initView() {
        human_tit = findViewById(R.id.human_tit);
        human_tit.setTitle(getIntent().getStringExtra("METHOD"));

        human_btn_export = findViewById(R.id.human_btn_export);
        human_btn_export.setOnClickListener(v->{
            FileReadWriteTask fileReadWriteTask = new FileReadWriteTask();
            fileReadWriteTask.execute();
        });

        human_gv_data = findViewById(R.id.human_gv_data);

        human_tv_real = findViewById(R.id.human_tv_real);
        human_tv_choose = findViewById(R.id.human_tv_choose);

        setResult(getIntent().getIntExtra("loopRange", 0),
                getIntent().getFloatExtra("deltaMass", 0),
                getIntent().getDoubleExtra("rmsResponse", 0),
                getIntent().getDoubleArrayExtra("simuRMS"));
        return true;
    }

    @Override
    protected boolean initData() {
        return true;
    }

    @Override
    protected BasePresenter genPresenter() {
        return null;
    }


    private void setResult(int loopRange, float deltaMass, double rmsResponse, double[] simuRMS) {
        runOnUiThread(() -> {
            human_gv_data.getViewport().setMaxXAxisSize(loopRange * deltaMass / 1000);
            //graph.getViewport().setMaxYAxisSize(100.0D);
            human_gv_data.getViewport().setXAxisBoundsManual(true);
            human_gv_data.getViewport().setYAxisBoundsManual(true);

            NumberFormat nf = NumberFormat.getInstance();
            nf.setMinimumFractionDigits(2);
            nf.setMinimumIntegerDigits(1);
            human_gv_data.getGridLabelRenderer().setLabelFormatter(new DefaultLabelFormatter(null, nf));
            human_gv_data.getGridLabelRenderer().setPadding(32);

            human_gv_data.getViewport().setMinX(0);
            human_gv_data.getViewport().setMaxX(loopRange * deltaMass / 1000);
            human_gv_data.getViewport().setMinY(0);
            human_gv_data.getViewport().setMaxY(5 * rmsResponse);
            human_gv_data.getViewport().setScalable(true);
            human_gv_data.getViewport().setScalableY(true);
            oPoint.setSize(3);
            responseSeries.setThickness(3);
            simuSeries.setThickness(3);
            simuSeries.setColor(Color.BLUE);
            responseSeries.setColor(Color.RED);
            human_gv_data.setBackgroundColor(Color.WHITE);
            oPoint.setTitle("原点");
            responseSeries.setTitle("真实响应");
            simuSeries.setTitle("测试结果");
            human_gv_data.getLegendRenderer().setBackgroundColor(Color.TRANSPARENT);
            human_gv_data.getLegendRenderer().setVisible(true);
            human_gv_data.getLegendRenderer().setTextSize(18);
            human_gv_data.getLegendRenderer().setTextColor(R.color.main_grey_2);
            human_gv_data.getLegendRenderer().setAlign(LegendRenderer.LegendAlign.TOP);
            human_gv_data.getGridLabelRenderer().setHorizontalAxisTitle("时间(s)");
            human_gv_data.getGridLabelRenderer().setVerticalAxisTitle("幅值(g)");
            human_gv_data.getGridLabelRenderer().setHorizontalAxisTitleTextSize(24);
            human_gv_data.getGridLabelRenderer().setVerticalAxisTitleTextSize(24);
            human_gv_data.addSeries(oPoint);
            human_gv_data.addSeries(responseSeries);
            human_gv_data.addSeries(simuSeries);

            human_tv_real.setText("" + rmsResponse);
            oPoint.appendData(new DataPoint(0, 0), true, 1000);
            responseSeries.appendData(new DataPoint(0, rmsResponse), true, 1000);
            responseSeries.appendData(new DataPoint(loopRange * deltaMass / 1000, rmsResponse), true, 1000);
            boolean hasIntersection = false;
            double intersectionX = 0d, intersectionY = 0d;
            for (int i = 0; i < loopRange; i++) {
                simuSeries.appendData(new DataPoint((i + 1) * deltaMass / 1000, simuRMS[i]), true, 1000);
                if (i > 0 && !hasIntersection && simuRMS[i - 1] >= rmsResponse && simuRMS[i] <= rmsResponse) {
                    hasIntersection = true;
                    intersectionX = (i + 1) * deltaMass / 1000;
                    intersectionY = simuRMS[i];
                }
            }

            if (hasIntersection) {
                human_tv_choose.setText("(" + intersectionX + ", " + intersectionY + ")");
            } else {
                human_tv_choose.setText("没有交点");
            }
        });
    }


    private class FileReadWriteTask extends AsyncTask<Void, Void, Void> {
        private LoadingDialog loadingDialog = null;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loadingDialog = new LoadingDialog(HumanActivity.this);
            loadingDialog.showDialog(HumanActivity.this, "正在输出报告...", 5);
        }

        @Override
        protected Void doInBackground(Void... voids) {
            SimpleDateFormat sdf = new SimpleDateFormat();
            sdf.applyPattern("yyyy-MM-dd HH:mm:ss");
            Date date = new Date();

            Map<String, String> replacements = new HashMap<>();
            replacements.put("【时间】", sdf.format(date));
            replacements.put("【姓名】", UserManager.getInstance().getUsername());
            replacements.put("【响应】", human_tv_real.getText().toString().trim());
            replacements.put("【交点】", human_tv_choose.getText().toString().trim());
            Bitmap bitmap = PoiUtil.loadBitmapFromView(human_gv_data);

            synchronized (PoiUtil.class) {
                PoiUtil.replaceFieldsWithImage(bitmap, HumanActivity.this, Constants.METHOD_HUMAN,
                        sdf.format(date) + ".docx", replacements);
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void unused) {
            super.onPostExecute(unused);
            if(loadingDialog != null) loadingDialog.dismiss();
            ToastUtil.show("报告已保存");
        }
    }
}